package com.zhl.study.service;

import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @description TODO
 * @Author: z156940l@outlook.com
 * @className AuthorsService
 * @Date: 2023/3/21 23:57
 */
@Service
@Slf4j
public class BcmpFileInfoService {
    private final SqlSessionTemplate sqlSessionTemplate;
    private final BcmpFileInfoMapper bcmpFileInfoMapper;

    public BcmpFileInfoService(SqlSessionTemplate sqlSessionTemplate, BcmpFileInfoMapper bcmpFileInfoMapper) {
        this.sqlSessionTemplate = sqlSessionTemplate;
        this.bcmpFileInfoMapper = bcmpFileInfoMapper;
    }

    /**
     * stream读数据写文件方式
     *
     * @param httpServletResponse
     * @throws IOException
     */
    public void streamDownload(HttpServletResponse httpServletResponse)
            throws IOException {

        CustomResultHandler customResultHandler = new CustomResultHandler(new DownloadProcessor(httpServletResponse));
        sqlSessionTemplate.select(
                "com.zhl.study.service.BcmpFileInfoMapper.streamByExample", customResultHandler);
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }

    /**
     * 传统下载方式
     *
     * @param httpServletResponse
     * @throws IOException
     */
    public void traditionDownload(HttpServletResponse httpServletResponse)
            throws IOException {
        List<BcmpFileInfo> authors = bcmpFileInfoMapper.selectByExample();
        DownloadProcessor downloadProcessor = new DownloadProcessor(httpServletResponse);
        authors.forEach(downloadProcessor::processData);
        httpServletResponse.getWriter().flush();
        httpServletResponse.getWriter().close();
    }
}
